package com.kehutong.payfees.service;

import com.kehutong.common.ExcelHeaders;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.*;
import com.kehutong.payfees.enums.BillEnableState;
import com.kehutong.payfees.enums.ChargeModeType;
import com.kehutong.payfees.enums.ChooseType;
import com.kehutong.payfees.enums.ItemChargeModeType;
import com.kehutong.payfees.util.BasicClient;
import com.kehutong.payfees.util.ExcelUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 处理临时收费
 */
@WebService("/payfees/charge/choose")
public class ChargeChooseServiceImpl{

    @Inject
    private JdbcSession sqlSession;
    @Inject
    private BasicClient basicClient;

    public Object page(JSONObject jsonObject) {
        return this.findChargeChoosePage(jsonObject);
    }

    public Object get(String id) {
        return Result.success(Pool.get(ChargeChoose.class, id));
    }

    public Object delete(String id) {
        ChargeChoose setting = Pool.get(ChargeChoose.class, id);

        if (Objects.nonNull(setting)) {
            setting.setDeleted(true);
            sqlSession.updateById(setting);
        }

        return Result.success();
    }

    public Object updateEnable(JSONObject jsonObject) {
        ChargeChoose entity = sqlSession.findOne(ChargeChoose.class)
                .eq(jsonObject, "id")
                .exe();
        if (jsonObject.getBoolean("enable")) {
            entity.setEnableState(BillEnableState.ENABLE);
        } else {
            entity.setEnableState(BillEnableState.UNUSED);
        }
        sqlSession.updateById(entity);

        return Result.success();
    }

    public Object updateEnableAll(JSONObject jsonObject) {
        List<ChargeChoose> entitys = sqlSession.findArray(ChargeChoose.class)
                .in("id", jsonObject.getJSONArray("ids"))
                .exe();

        entitys.forEach(entity->{
            if (jsonObject.getBoolean("enable")) {
                entity.setEnableState(BillEnableState.ENABLE);
            } else {
                entity.setEnableState(BillEnableState.UNUSED);
            }
        });

        sqlSession.updateById(entitys);

        return Result.success();
    }

    public Object download(JSONObject jsonObject) throws IOException {
        List<ChargeChoose> list = this.findChargeChooseList(jsonObject);

        if (list.isEmpty()) {
            return Result.error(0, "无记录导出");
        }

        XSSFWorkbook wb = generateWorkBook(list, jsonObject);

        File tmpFile = ExcelUtil.writeXlsFile(wb, "标准选用导出", ".xlsx");
        return Result.download(tmpFile);
    }

    public Object update(Token token, ChargeChoose entity) throws Exception {
        ChargeStandard standard = Pool.get(ChargeStandard.class, entity.getStandardId());
        entity.setStandardName(standard.getName());
        entity.setChargeMode(standard.getChargeMode());
        entity.setUnitPrice(standard.getUnitPrice());
        entity.setComputeType(standard.getComputeType());

        ChargeFeeType feeType = Pool.get(ChargeFeeType.class, entity.getFeeTypeId());
        entity.setFeeTypeName(feeType.getName());

        entity.setPrice(standard.getPrice());

        JSONObject house = basicClient.getHouseById(token, entity.getHouseNo());
        if(entity.getChargeMode() == ChargeModeType.AREA){
            entity.setAmount(house.getBigDecimal("payArea"));
            if(Objects.nonNull(entity.getAmount())){
                entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
            }else{
                entity.setTotal(null);
            }
        }else if(entity.getChargeMode() == ChargeModeType.COVER){
            entity.setAmount(new BigDecimal(1));
            if(Objects.nonNull(entity.getAmount())){
                entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
            }else{
                entity.setTotal(null);
            }
        }else if(entity.getChargeMode() == ChargeModeType.TIER){
            if(Objects.nonEmpty(house.getString("floorName"))){
                // 字符串截取 **楼前面的数字
                String floorNumber = getQuantity(house.getString("floorName"));
                entity.setAmount(new BigDecimal(floorNumber));
                if(Objects.nonNull(entity.getAmount())){
                    entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
                }else{
                    entity.setTotal(null);
                }
            }
        }else if(entity.getChargeMode() == ChargeModeType.AMOUNTLADDER){// 用量阶梯价
            entity.setAmount(null);
            entity.setTotal(null);
        } else if(entity.getChargeMode() == ChargeModeType.AREALADDER){// 面积阶梯价
            entity.setAmount(house.getBigDecimal("payArea"));
            if(Objects.nonNull(entity.getAmount())) {
                this.getTotal(entity);
            }else{
                entity.setTotal(null);
            }
        } else if(entity.getChargeMode() == ChargeModeType.TIERLADDER){// 层数阶梯价
            // 字符串截取 **楼前面的数字
            String floorNumber = getQuantity(house.getString("floorName"));
            entity.setAmount(new BigDecimal(floorNumber));
            if(Objects.nonNull(entity.getAmount())) {
                this.getTotal(entity);
            }else{
                entity.setTotal(null);
            }
        } else{
            entity.setAmount(null);
            entity.setTotal(null);
        }

        setDepartmentNo(entity, token.getCompanyNo());

        sqlSession.updateById(entity);

        return Result.success();
    }

    public Object save(Token token, JSONObject jsonObject) throws Exception {
        JSONArray nodeArray =jsonObject.getJSONArray("nodeList");
        JSONArray checkedArray =jsonObject.getJSONArray("checkedList");
        ChooseType chooseType = EnumUtil.getEnum(ChooseType.class,jsonObject.getString("chooseType"));

        Set<String> buildingNos = new HashSet<>();
        Set<String> feeTypeNos = new HashSet<>();
        Set<String> communityNos = new HashSet<>();
        Set<String> standardNos = new HashSet<>();

        Set<String> houses = new HashSet<>();
        for (int i = 0; i < nodeArray.size(); i++) {
            JSONObject nodeJson = nodeArray.getJSONObject(i);
            for (int j = 0; j < checkedArray.size(); j++) {
                String id = checkedArray.getString(j);

                if(chooseType == ChooseType.CONVENTIONAL){
                    JSONObject data = basicClient.getHouseById(token, id);
                    buildingNos.add(data.getString("buildNo"));
                    communityNos.add(data.getString("communityNo"));
                    houses.add(id);
                } else {
                    ChargeUserInstrument ins = Pool.get(ChargeUserInstrument.class, id);
                    JSONObject data = basicClient.getHouseById(token, ins.getHouseId());
                    buildingNos.add(data.getString("buildNo"));
                    communityNos.add(data.getString("communityNo"));
                    houses.add(ins.getHouseId());
                }
                feeTypeNos.add(nodeJson.getString("feeTypeId"));
                standardNos.add(nodeJson.getString("standardId"));

            }
        }

        // 获取费项信息
        List<ChargeFeeType> feeTypes = sqlSession.findArray(ChargeFeeType.class)
                .in("id", feeTypeNos)
                .exe();
        Map<String,ChargeFeeType> feeTypeMap = new HashMap<>();
        feeTypes.forEach(item->{
            feeTypeMap.put(item.getId(), item);
        });

        List<String> errMsgs = new ArrayList<>();
        // 全量增量控制
        if(jsonObject.getBoolean("type")){
            List<ChargeChoose> chooses = sqlSession.findArray(ChargeChoose.class)
                    .in("houseNo", houses)
                    .eq("chooseType", chooseType.getId())
                    .exe();
            sqlSession.deleteById(chooses);
        }

        Map<String,String> buildMap = getBuildingDto(token, buildingNos);

        JSONArray jsonArray = basicClient.getCommunityByIds(token, new ArrayList<>(communityNos));
        Map<String,JSONObject> communityMap = new HashMap<>();
        jsonArray.forEach(item->{
            JSONObject obj = (JSONObject) item;
            communityMap.put(obj.getString("id"), obj);
        });

        // 获取费项标准
        List<ChargeStandard> standards = sqlSession.findArray(ChargeStandard.class)
                .eq(jsonObject, "communityNo")
                .in("id", standardNos)
                .exe();
        Map<String,ChargeStandard> standardMap = new HashMap<>();
        standards.forEach(item->{
            standardMap.put(item.getId(), item);
        });

        for (int i = 0; i < nodeArray.size(); i++) {
            JSONObject nodeJson = nodeArray.getJSONObject(i);
            for (int j = 0; j < checkedArray.size(); j++) {
                ChargeChoose entity = Pool.newInstance(ChargeChoose.class);
                String id = checkedArray.getString(j);

                ChargeUserInstrument ins = null;
                JSONObject data;
                if(chooseType == ChooseType.CONVENTIONAL) {
                    data = basicClient.getHouseById(token, id);
                    entity.setHouseNo(id);
                }else{
                    ins = Pool.get(ChargeUserInstrument.class, id);
                    final String houseId = ins.getHouseId();
                    ChargeInstrumentType insType = Pool.get(ChargeInstrumentType.class, ins.getInstrumentTypeId());
                    data = basicClient.getHouseById(token, houseId);
                    entity.setInstrumentId(id);
                    entity.setInstrumentNo(ins.getInstrumentNo());
                    entity.setInstrumentTypeName(insType.getName());
                    entity.setInstrumentTypeId(ins.getInstrumentTypeId());
                    entity.setHouseNo(houseId);
                }
                FindArray<ChargeChoose> find = sqlSession.findArray(ChargeChoose.class)
                        .eq("communityNo", data.getString("communityNo"))
                        .eq(nodeJson,"feeTypeId");
                if(chooseType == ChooseType.INSTRUMENT){
                    find.eq("instrumentNo", ins.getInstrumentNo());
                }
                find.eq("houseNo", data.getString("id"))
                        .eq("chooseType", chooseType.getId())
                        .eq("deleted", false);

                List<ChargeChoose> list = find.exe();

                if(Objects.nonEmpty(list)){
                    StringBuilder builder = new StringBuilder();
                    builder.append("房间信息：")
                            .append(basicClient.getHouseInfo(data));
                    if(chooseType == ChooseType.INSTRUMENT){
                        builder.append(",仪表编号：")
                                .append(ins.getInstrumentNo());
                    }
                    builder.append(",配置了重复的费项,")
                            .append("费项名称：")
                            .append(feeTypeMap.get(nodeJson.getString("feeTypeId")).getName());
                    errMsgs.add(builder.toString());
                    continue;
                }

                entity.setHouseName(data.getString("floorName") + data.getString("name"));

                entity.setCommunityNo(data.getString("communityNo"));
                entity.setCommunityName(communityMap.get(data.getString("communityNo")).getString("name"));

                entity.setBuildingNo(data.getString("buildNo"));
                entity.setBuildingName(buildMap.get(data.getString("buildNo")));

                entity.setFeeTypeId(nodeJson.getString("feeTypeId"));
                entity.setFeeTypeName(feeTypeMap.get(nodeJson.getString("feeTypeId")).getName());

                entity.setStandardId(nodeJson.getString("standardId"));
                entity.setStandardName(standardMap.get(nodeJson.getString("standardId")).getName());

                entity.setOwnerName(data.getString("ownerName"));
                entity.setEnableState(BillEnableState.ENABLE);
                entity.setChooseType(chooseType);

                entity.setPrice(nodeJson.getBigDecimal("price"));

                ChargeModeType chargeMode = EnumUtil.getEnum(ChargeModeType.class,nodeJson.getString("chargeMode"));
                entity.setChargeMode(chargeMode);

                ChargeStandard standard = Pool.get(ChargeStandard.class, nodeJson.getString("standardId"));
                entity.setUnitPrice(standard.getUnitPrice());
                entity.setComputeType(standard.getComputeType());

                setDepartmentNo(entity, token.getCompanyNo());

                if(chargeMode == ChargeModeType.AREA){
                    entity.setAmount(data.getBigDecimal("payArea"));
                    if(Objects.nonNull(entity.getAmount())){
                        entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
                    }else{
                        entity.setTotal(null);
                    }
                }else if(chargeMode == ChargeModeType.COVER){
                    entity.setAmount(new BigDecimal(1));
                    if(Objects.nonNull(entity.getAmount())){
                        entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
                    }else{
                        entity.setTotal(null);
                    }
                }else if(chargeMode == ChargeModeType.TIER){
                    if(Objects.nonEmpty(data.getString("floorName"))){
                        // 字符串截取 **楼前面的数字
                        String floorNumber = getQuantity(data.getString("floorName"));
                        entity.setAmount(new BigDecimal(floorNumber));
                        if(Objects.nonNull(entity.getAmount())){
                            entity.setTotal(BigDecimal.ZERO.add(entity.getPrice()).multiply(entity.getAmount()));
                        }else{
                            entity.setTotal(null);
                        }
                    }
                }else if(chargeMode == ChargeModeType.AMOUNTLADDER){// 用量阶梯价
                    entity.setAmount(null);
                    entity.setTotal(null);
                } else if(chargeMode == ChargeModeType.AREALADDER){// 面积阶梯价
                    entity.setAmount(data.getBigDecimal("payArea"));
                    if(Objects.nonNull(entity.getAmount())) {
                        this.getTotal(entity);
                    }else{
                        entity.setTotal(null);
                    }
                } else if(chargeMode == ChargeModeType.TIERLADDER){// 层数阶梯价
                    // 字符串截取 **楼前面的数字
                    String floorNumber = getQuantity(data.getString("floorName"));
                    entity.setAmount(new BigDecimal(floorNumber));
                    if(Objects.nonNull(entity.getAmount())) {
                        this.getTotal(entity);
                    }else{
                        entity.setTotal(null);
                    }
                } else{
                    entity.setAmount(null);
                    entity.setTotal(null);
                }
                sqlSession.insert(entity);
            }
        }

        return Result.success(errMsgs);
    }

    private Page<ChargeChoose> findChargeChoosePage(JSONObject jsonObject){
        return  sqlSession.findPage(ChargeChoose.class)
                .eq(jsonObject, "communityNo","feeTypeId","standardId","chargeMode","enableState","chooseType","instrumentNo","instrumentTypeId")
                .like(jsonObject,"buildingName", "unitName", "floorName", "houseName","ownerName")
                .eq("deleted", false)
                .order("createTime", "desc")
                .order("communityNo", "DESC")
                .order("buildingName", "ASC")
                .order("unitName", "ASC")
                .order("houseName", "ASC")
                .page(jsonObject).exe();
    }

    private List<ChargeChoose> findChargeChooseList(JSONObject jsonObject){
        return  sqlSession.findArray(ChargeChoose.class)
                .eq(jsonObject, "communityNo","feeTypeId","standardId","chargeMode","enableState","chooseType","instrumentNo","instrumentTypeId")
                .like(jsonObject,"buildingName", "unitName", "floorName", "houseName","ownerName")
                .eq("deleted", false)
                .order("createTime", "desc")
                .order("communityNo", "DESC")
                .order("buildingName", "ASC")
                .order("unitName", "ASC")
                .order("floorName", "ASC")
                .order("houseName", "ASC")
                .exe();
    }

    public XSSFWorkbook generateWorkBook(List<ChargeChoose> list, JSONObject jsonObject) {
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd"));

        Sheet sheet = wb.createSheet();

        Row headerRow = sheet.createRow(0);

        ChooseType chooseType = EnumUtil.getEnum(ChooseType.class,jsonObject.getString("chooseType"));

        if (chooseType == ChooseType.CONVENTIONAL) {
            for (int i = 0; i < ExcelHeaders.CHARGE_CHOOSE_CONVENTIONAL_EXECEL_HEADER.length; i++) {
                headerRow.createCell(i).setCellValue(ExcelHeaders.CHARGE_CHOOSE_CONVENTIONAL_EXECEL_HEADER[i]);
            }
        }else{
            for (int i = 0; i < ExcelHeaders.CHARGE_CHOOSE_INSTRUMENT_EXECEL_HEADER.length; i++) {
                headerRow.createCell(i).setCellValue(ExcelHeaders.CHARGE_CHOOSE_INSTRUMENT_EXECEL_HEADER[i]);
            }
        }

        int cellNum = 0;
        for (int i = 0; i < list.size(); i++) {
            cellNum = 0;
            ChargeChoose entity = list.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(cellNum++).setCellValue(entity.getCommunityName());
            StringBuilder builder = new StringBuilder();
            builder.append(entity.getBuildingName()).append("*");
            if(Objects.nonNull(entity.getUnitName())){
                builder.append(entity.getUnitName()).append("*");
            }
            builder.append(entity.getHouseName());
            row.createCell(cellNum++).setCellValue(builder.toString());
            row.createCell(cellNum++).setCellValue(entity.getOwnerName());
            if(chooseType == ChooseType.INSTRUMENT){
                row.createCell(cellNum++).setCellValue(entity.getInstrumentNo());
                row.createCell(cellNum++).setCellValue(entity.getInstrumentTypeName());
            }
            row.createCell(cellNum++).setCellValue(entity.getFeeTypeName());
            row.createCell(cellNum++).setCellValue(entity.getStandardName());
            row.createCell(cellNum++).setCellValue(entity.getChargeMode().getDesc());
            if (chooseType == ChooseType.CONVENTIONAL) {
                row.createCell(cellNum++).setCellValue(Objects.nonNull(entity.getAmount()) ? entity.getAmount().toString() : "");
                row.createCell(cellNum++).setCellValue(Objects.nonNull(entity.getPrice()) ? entity.getPrice().toString() : "");
                row.createCell(cellNum++).setCellValue(Objects.nonNull(entity.getTotal()) ? entity.getTotal().toString() : "");
            }else{
                row.createCell(cellNum++).setCellValue(Objects.nonNull(entity.getPrice()) ? entity.getPrice().toString() : "");
            }
            row.createCell(cellNum++).setCellValue(entity.getEnableState().getDesc());
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    public static String getQuantity(String regular){
        int index = 0;
        for (int i = 0; i < regular.length(); i++) {
            char c = regular.charAt(i);
            if (Character.isDigit(c)) {
                if (i == regular.length() - 1) {
                    index = i + 1;
                } else {
                    index = i;
                }
                continue;
            } else {
                index = i;
                break;
            }
        }
        return regular.substring(0, index);
    }

    private Map<String,String> getBuildingDto(Token token, Set<String> strs) throws Exception {
        JSONArray data = basicClient.getBuildByIds(token, new ArrayList<>(strs));
        if(Objects.isNull(data)){
            return new HashMap<>();
        }

        Map<String,String> resultMap = new HashMap<>();
        data.forEach(item ->{
            JSONObject json = (JSONObject) item;
            resultMap.put(json.getString("id"), json.getString("name"));
        });

        return resultMap;
    }

    public void getTotal(ChargeChoose choose){
        List<ChargeStandardItem> standardItems = sqlSession.findArray(ChargeStandardItem.class)
                .eq("standardId", choose.getStandardId())
                .order("startAmount","asc")
                .exe();
        BigDecimal upHighPrice = BigDecimal.ZERO;
        BigDecimal upEndAmount = BigDecimal.ZERO;
        for (int i = 0;i < standardItems.size();i++) {
            ChargeStandardItem item = standardItems.get(i);
            // 第一阶
            if(i == 0 && choose.getAmount().compareTo(item.getStartAmount()) < 0){
                choose.setTotal(new BigDecimal(0));
                continue;
            }else if(i == 0){
                upEndAmount = item.getStartAmount();
            }
            // 不是最后一阶
            if(Objects.nonNull(item.getEndAmount())){
                if(choose.getAmount().compareTo(item.getStartAmount()) >= 0 &&
                        choose.getAmount().compareTo(item.getEndAmount()) <= 0){
                    // 一口价
                    if(item.getChargeMode() == ItemChargeModeType.SPECIFY) {
                        choose.setTotal(item.getPrice());
                        continue;
                    }else{
                        choose.setTotal(upHighPrice.add((choose.getAmount().subtract(upEndAmount)).multiply(item.getPrice())));
                        continue;
                    }
                }else{
                    // 一口价
                    if(item.getChargeMode() == ItemChargeModeType.SPECIFY) {
                        upHighPrice = item.getPrice();
                        upEndAmount = item.getEndAmount();
                        // 增量价
                    }else{
                        upHighPrice = upHighPrice.add((item.getEndAmount().subtract(upEndAmount)).multiply(item.getPrice()));
                        upEndAmount = item.getEndAmount();
                    }
                }
                // 最后一阶
            }else{
                if(choose.getAmount().compareTo(item.getStartAmount()) >= 0){
                    // 一口价
                    if(item.getChargeMode() == ItemChargeModeType.SPECIFY) {
                        choose.setTotal(item.getPrice());
                        // 增量价
                    }else{
                        choose.setTotal(upHighPrice.add((choose.getAmount().subtract(upEndAmount)).multiply(item.getPrice())));
                    }
                }
            }
        }
    }

    @ReqMapping("/updateChargeSetting")
    public void updateChargeSetting(JSONObject house){
        List<ChargeChoose> chooses = sqlSession.findArray(ChargeChoose.class)
                .eq("communityNo", house.getString("communityNo"))
                .eq("houseNo", house.getString("id"))
                .exe();
        chooses.forEach(choose->{
            choose.setHouseName(house.getString("floorName") + house.getString("name"));
            choose.setBuildingNo(house.getString("buildNo"));
            choose.setBuildingName(house.getString("buildName"));
            choose.setUnitName(house.getString("unitName"));
            choose.setOwnerName(house.getString("ownerName"));

            if(choose.getChargeMode() == ChargeModeType.AREA){
                choose.setAmount(house.getBigDecimal("payArea"));
                if(Objects.nonNull(choose.getAmount())){
                    choose.setTotal(BigDecimal.ZERO.add(choose.getPrice()).multiply(choose.getAmount()));
                }else{
                    choose.setTotal(null);
                }
            }else if(choose.getChargeMode() == ChargeModeType.COVER){
                choose.setAmount(new BigDecimal(1));
                if(Objects.nonNull(choose.getAmount())){
                    choose.setTotal(BigDecimal.ZERO.add(choose.getPrice()).multiply(choose.getAmount()));
                }else{
                    choose.setTotal(null);
                }
            }else if(choose.getChargeMode() == ChargeModeType.TIER){
                if(Objects.nonEmpty(house.getString("floorName"))){
                    // 字符串截取 **楼前面的数字
                    String floorNumber = getQuantity(house.getString("floorName"));
                    choose.setAmount(new BigDecimal(floorNumber));
                    if(Objects.nonNull(choose.getAmount())){
                        choose.setTotal(BigDecimal.ZERO.add(choose.getPrice()).multiply(choose.getAmount()));
                    }else{
                        choose.setTotal(null);
                    }
                }
            }else if(choose.getChargeMode() == ChargeModeType.AMOUNTLADDER){// 用量阶梯价
                choose.setAmount(null);
                choose.setTotal(null);
            } else if(choose.getChargeMode() == ChargeModeType.AREALADDER){// 面积阶梯价
                choose.setAmount(house.getBigDecimal("payArea"));
                if(Objects.nonNull(choose.getAmount())) {
                    this.getTotal(choose);
                }else{
                    choose.setTotal(null);
                }
            } else if(choose.getChargeMode() == ChargeModeType.TIERLADDER){// 层数阶梯价
                // 字符串截取 **楼前面的数字
                String floorNumber = getQuantity(house.getString("floorName"));
                choose.setAmount(new BigDecimal(floorNumber));
                if(Objects.nonNull(choose.getAmount())) {
                    this.getTotal(choose);
                }else{
                    choose.setTotal(null);
                }
            } else{
                choose.setAmount(null);
                choose.setTotal(null);
            }
        });
        sqlSession.updateById(chooses);


        List<ChargeMonthRead> monthReads = sqlSession.findArray(ChargeMonthRead.class)
                .eq("communityNo", house.getString("communityNo"))
                .eq("houseId", house.getString("id"))
                .exe();

        monthReads.forEach(item ->{
            item.setContactName(house.getString("ownerName"));
        });
        sqlSession.updateById(monthReads);

        List<ChargeUserInstrument> instruments = sqlSession.findArray(ChargeUserInstrument.class)
                .eq("communityNo", house.getString("communityNo"))
                .eq("houseId", house.getString("id"))
                .exe();
        instruments.forEach(item->{
            item.setContactName(house.getString("ownerName"));
        });
        sqlSession.updateById(instruments);

    }

    private void setDepartmentNo(ChargeChoose entity, String companyNo) throws Exception {
        JSONObject community = basicClient.getCommunityById(companyNo,
                entity.getCommunityNo());
        if(Objects.nonEmpty(community)){
            String parent_id = community.getString("parent_id");
            if(Objects.nonEmpty(parent_id)){
                entity.setDepartmentNo(parent_id);
            }
            JSONArray parent_ids = community.getJSONArray("parent_ids");
            if(Objects.nonEmpty(parent_ids)){
                List<String> departmentNos = JSONObject.parseArray(parent_ids.toJSONString(), String.class);
                entity.setDepartmentNos(departmentNos);
            }
        }
    }
}
